package com.woniu.controller;

import com.woniu.been.entity.CourseCategories;
import com.woniu.been.entity.CourseChapters;
import com.woniu.been.entity.Courses;
import com.woniu.service.CourseCategoriesService;
import com.woniu.service.CourseChaptersService;
import com.woniu.service.CoursesService;
import com.woniu.service.impl.CourseService;
import com.woniu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/course-data")
@CrossOrigin(origins = {"http://localhost:5174", "http://localhost:5173"}, allowCredentials = "true")
public class CourseDataController {

    @Autowired
    private CourseCategoriesService courseCategoriesService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private CoursesService coursesService;

    @Autowired
    private CourseChaptersService courseChaptersService;

    /**
     * 获取所有顶级课程大类
     * URL: /api/course-data/categories
     * @return 课程大类列表
     */
    @GetMapping("/categories")
    public Result<List<CourseCategories>> getAllCategories() {
        try {
            log.info("开始获取课程大类列表");
            List<CourseCategories> categories = courseCategoriesService.getAllTopLevelCategories();
            log.info("成功获取课程大类列表: {}", categories);
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取课程大类失败", e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据课程大类名称获取课程列表
     * URL: /api/course-data/categories/{categoryName}/courses
     * @param categoryName 课程大类名称
     * @return 课程列表
     */
    @GetMapping("/categories/{categoryName}/courses")
    public Result<List<Courses>> getCoursesByCategoryName(@PathVariable String categoryName) {
        try {
            List<Courses> courses = coursesService.getCoursesByCategoryName(categoryName);
            return Result.success(courses);
        } catch (Exception e) {
            log.error("根据分类名称获取课程失败, categoryName: {}", categoryName, e);
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 根据课程ID获取章节列表
     * URL: /api/course-data/courses/{courseId}/chapters
     * @param courseId 课程ID
     * @return 章节列表
     */
    @GetMapping("/courses/{courseId}/chapters")
    public Result<List<CourseChapters>> getChaptersByCourseId(@PathVariable Integer courseId) {
        try {
            List<CourseChapters> chapters = courseChaptersService.getChaptersByCourseId(courseId);
            return Result.success(chapters);
        } catch (Exception e) {
            log.error("根据课程ID获取章节失败, courseId: {}", courseId, e);
            return Result.fail(e.getMessage());
        }
    }
} 